package io.renren;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Description
 *
 * @author ext.mahaifu1
 * @ClassName ObjectComparator
 * @date 2024-01-15
 */
public class ObjectComparator {
    public static boolean areFieldsEqual(Object obj1, Object obj2) throws IllegalAccessException {
        // 检查对象不为空且是同一类型
        if (obj1 == null || obj2 == null || !obj1.getClass().equals(obj2.getClass())) {
            return false;
        }
        // 获取obj1的所有字段
        Field[] fields = obj1.getClass().getDeclaredFields();
//        // 包括其父类的字段
//        Class<?> superClass = obj1.getClass().getSuperclass();
//        while (superClass != null) {
//            fields = Arrays.copyOf(fields, fields.length + superClass.getDeclaredFields().length);
//            System.arraycopy(superClass.getDeclaredFields(), 0, fields, fields.length - superClass.getDeclaredFields().length, superClass.getDeclaredFields().length);
//            superClass = superClass.getSuperclass();
//        }

        // 设置访问权限，以便获取私有字段
        for (Field field : fields) {
            field.setAccessible(true);
            // 获取两个对象对应字段的值
            Object value1 = field.get(obj1);
            Object value2 = field.get(obj2);
            // 比较字段值是否相等
            if (!Objects.equals(value1, value2)) {
                return false;
            }
        }
        // 如果所有字段都比较完毕且没有发现不相等，则返回true
        return true;
    }

    public static void main(String[] args) throws IllegalAccessException {
        // 测试用例
//        YourClass objA = new YourClass("value1", new BigDecimal("1.1"),"value1");
//        YourClass objB = new YourClass("value1", new BigDecimal("1.1"),"value1");


//        List<YourClass> objs1 = new ArrayList<>();
//        YourClass obj1 = new YourClass("value1", "value2");
//        YourClass obj2 = new YourClass("value1", "value3");
//        YourClass obj3 = new YourClass("value1", "value4");
//        objs1.add(obj1);
//        objs1.add(obj2);
//        objs1.add(obj3);
//
//        List<YourClass> objs2 = new ArrayList<>();
//        YourClass obj11 = new YourClass("value1", "value2");
//        YourClass obj12 = new YourClass("value1", "value3");
//        YourClass obj13 = new YourClass("value3", "value4");
//        objs2.add(obj11);
//        objs2.add(obj12);
//        objs2.add(obj13);



//        System.out.println(areFieldsEqual(objA, objB));  // 输出false，因为第二个字段值不同
    }
}

// 假设有一个类YourClass
//class YourClass {
//    private String field1;
//    private BigDecimal field2;
//
//    private String field3;
//
//    public YourClass(String field1, BigDecimal field2,String field3) {
//        this.field1 = field1;
//        this.field2 = field2;
//        this.field3 = field3;
//    }
//}